package com.bbx.demo.heartbeat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;
import java.util.Scanner;

public class HeartbeatClient {
    private String host = "192.168.2.252";
    private int port = 8092;

    public HeartbeatClient() {
    }

    public static void main (String [] args) throws InterruptedException {
        HeartbeatClientHandler heartbeatClientHandler = new HeartbeatClientHandler();
        new HeartbeatClient().start(heartbeatClientHandler);
    }


    public void start (ChannelHandler channelHandler ) throws InterruptedException {
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventExecutors).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8"))).addLast(new StringEncoder(CharsetUtil.UTF_8)).addLast(channelHandler);
            }
        });
        ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
        Scanner scanner = new Scanner(System.in);
        while (true){
            String s = scanner.nextLine();
            if ("exis".equals(s)) {
                channelFuture.channel().writeAndFlush(s).addListener(ChannelFutureListener.CLOSE);
            } else {
                channelFuture.channel().writeAndFlush(s);
            }
        }
    }



}
